package service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dto.BidRequest;
import dto.BidResult;
import model.BidRecord;
import model.User;
import repository.BidRecordRepository;
import repository.UserRepository;

@Service
public class BiddingService {

    @Autowired
    private BidRecordRepository bidRecordRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BondServiceClient bondServiceClient;

    public String placeBid(Long userId) {
        BigDecimal amount = null;
        BidRequest request = new BidRequest(amount);
        String auctionId = null;
        BidResult result = bondServiceClient.placeBid(auctionId, request);

        if (result.isSuccess()) {
            User user = userRepository.findById(userId).orElseThrow();
            BidRecord record = new BidRecord();
            record.setUser(user);
            record.setAuctionId(auctionId);
            record.setAmount(amount);
            record.setBidTime(LocalDateTime.now());
            bidRecordRepository.save(record);
            return "出价成功";
        } else {
            return "出价失败：" + result.getMessage();
        }
    }

    public String cancelBid(Long bidId) {
        BidRecord record = bidRecordRepository.findById(bidId).orElseThrow();
        record.setActive(false);
        bidRecordRepository.save(record);
        return "出价已撤销";
    }

    public List<BidRecord> getUserBids(Long userId) {
        return bidRecordRepository.findByUserIdAndActiveTrue(userId);
    }

    public boolean placeBid(BidRequest bidRequest) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
